Page({
  data: {
    userInfo: {},
    studentId: '',
    nickName: '',
    showInviteModal: false
  },

  onShareAppMessage() {
    return {};
  },

  onShow() {
    this.getUserInfo();
  },

  onLoad() {
    this.getUserInfo();
  },

  getUserInfo() {
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    console.log('获取到的用户信息：', userInfo); // 添加日志
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        studentId: userInfo.studentId || '',
        nickName: userInfo.nickName || '用户'
      });
    } else {
      this.setData({
        nickName: '用户'
      });
    }
  },

  // 跳转到定制页面
  handleCustomize() {
    wx.navigateTo({
      url: '../customize/index'
    });
  },

  // 跳转到查询页面
  handleQuery() {
    wx.navigateTo({
      url: '../style-detail/index'
    });
  },

  // 跳转到签领页面
  handleReceipt() {
    wx.navigateTo({
      url: '../../common/confirm-receipt/index'
    });
  },

  // 处理加入班级
  handleJoinClass() {
    this.setData({
      showInviteModal: true
    });
  },

  // 处理关闭弹窗
  handleCloseModal() {
    this.setData({
      showInviteModal: false
    });
  },

  // 处理提交邀请码
  async handleSubmitInvite(e) {
    const { inviteCode, studentId } = e.detail;
    try {
      // 调用云函数验证邀请码
      const res = await wx.cloud.callFunction({
        name: 'verifyInviteCode',
        data: {
          inviteCode,
          studentId
        }
      });

      if (res.result.error) {
        wx.showToast({
          title: res.result.error,
          icon: 'none'
        });
        return;
      }

      // 更新用户信息
      const userInfo = this.data.userInfo;
      userInfo.studentId = studentId;
      userInfo.classId = res.result.classId;
      
      // 保存到本地存储
      wx.setStorageSync('userInfo', userInfo);
      
      // 更新页面显示
      this.setData({
        studentId,
        showInviteModal: false
      });

      wx.showToast({
        title: '加入班级成功',
        icon: 'success'
      });

    } catch (error) {
      console.error('验证邀请码失败:', error);
      wx.showToast({
        title: '验证失败，请重试',
        icon: 'none'
      });
    }
  }
});